package com.huaboot.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huaboot.commont.constant.Constant;
import com.huaboot.commont.core.ResultUtils;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.commont.exception.ErrorCode;
import com.huaboot.commont.page.PageResult;
import com.huaboot.framework.dataScope.DataScopeUtils;
import com.huaboot.framework.mybatis.interceptor.DataScope;
import com.huaboot.framework.security.user.LoginUser;
import com.huaboot.framework.security.utils.SecurityUtil;
import com.huaboot.system.convert.SysUserConvert;
import com.huaboot.system.entity.SysUserEntity;
import com.huaboot.system.enums.SuperAdminEnum;
import com.huaboot.system.mapper.SysUserMapper;
import com.huaboot.system.query.SysRoleUserQuery;
import com.huaboot.system.query.SysUserQuery;
import com.huaboot.system.service.SysUserPostService;
import com.huaboot.system.service.SysUserRoleService;
import com.huaboot.system.service.SysUserService;
import com.huaboot.system.service.SysUserTokenService;
import com.huaboot.system.vo.SysUserPasswordVO;
import com.huaboot.system.vo.SysUserVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.huaboot.commont.exception.ErrorCode.USER_NO_EXIST;

/**
 * 用户管理
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    private final PasswordEncoder passwordEncoder;

    private final SysUserRoleService sysUserRoleService;

    private final SysUserPostService sysUserPostService;

    private final SysUserTokenService sysUserTokenService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserVO vo) {
        // 密码加密
        vo.setPassword(passwordEncoder.encode(vo.getPassword()));
        SysUserEntity entity = SysUserConvert.INSTANCE.convert(vo);
        entity.setSuperAdmin(SuperAdminEnum.NO.getValue());
        // 判断用户名是否存在
        SysUserEntity user = baseMapper.getByUsername(entity.getUsername());
        if (user != null) {
            throw new BusinessException(ErrorCode.USER_EXIST);
        }
        // 判断手机号是否存在
        user = baseMapper.getByMobile(entity.getMobile());
        if (user != null) {
            throw new BusinessException(ErrorCode.MOBILE_EXIST);
        }
        // 保存用户
        baseMapper.insert(entity);
        // 保存用户角色关系
        sysUserRoleService.saveOrUpdate(entity.getId(), vo.getRoleIdList());
        // 更新用户岗位关系
        sysUserPostService.saveOrUpdate(entity.getId(), vo.getPostIdList());
    }

    @Override
    public PageResult<SysUserVO> page(SysUserQuery query) {
        // 查询参数，设置数据权限
        Map<String, Object> params = getParams(query);

        // 分页查询
        Page<Object> objects = PageHelper.startPage(query.currentPage, query.size);
        params.put(Constant.PAGE, objects);

        // 数据列表
        List<SysUserEntity> list = baseMapper.getList(params);
        PageInfo<SysUserEntity> page = new PageInfo<>(list);
        return new PageResult<>(SysUserConvert.INSTANCE.convertList(page.getList()), page.getTotal());
    }

    @Override
    public SysUserVO getUserInfo(Long id) {
        SysUserEntity sysUserEntity = baseMapper.selectById(id);
        if (sysUserEntity == null){
            throw new BusinessException(USER_NO_EXIST);
        }
        SysUserVO vo = SysUserConvert.INSTANCE.convert(sysUserEntity);
        // 用户角色列表
        List<Long> roleIdList = sysUserRoleService.getRoleIdList(id);
        vo.setRoleIdList(roleIdList);
        // 用户岗位列表
        List<Long> postIdList = sysUserPostService.getPostIdList(id);
        vo.setPostIdList(postIdList);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        // 删除用户
        baseMapper.deleteBatchIds(idList);

        // 删除用户角色关系
        sysUserRoleService.deleteByUserIdList(idList);

        // 删除用户岗位关系
        sysUserPostService.deleteByUserIdList(idList);
    }

    @Override
    public void update(SysUserVO vo) {
        // 如果密码不为空，则进行加密处理
        if (StrUtil.isBlank(vo.getPassword())) {
            vo.setPassword(null);
        } else {
            vo.setPassword(passwordEncoder.encode(vo.getPassword()));
        }
        SysUserEntity entity = SysUserConvert.INSTANCE.convert(vo);
        // 判断用户名是否存在
        SysUserEntity user = baseMapper.getByUsername(entity.getUsername());
        if (user != null && !user.getId().equals(entity.getId())) {
            throw new BusinessException("用户名已经存在");
        }
        // 判断手机号是否存在
        user = baseMapper.getByMobile(entity.getMobile());
        if (user != null && !user.getId().equals(entity.getId())) {
            throw new BusinessException("手机号已经存在");
        }

        // 更新用户
        baseMapper.updateById(entity);
        // 更新用户角色关系
        sysUserRoleService.saveOrUpdate(entity.getId(), vo.getRoleIdList());

        // 更新用户岗位关系
        sysUserPostService.saveOrUpdate(entity.getId(), vo.getPostIdList());

        // 更新用户缓存权限
        sysUserTokenService.updateCacheAuthByUserId(entity.getId());
    }

    @Override
    public void updatePassword(SysUserPasswordVO vo) {
        // 原密码不正确
        LoginUser loginUser = SecurityUtil.getAuthentication();
        if (loginUser==null){
            throw new BusinessException("未找到登录用户");
        }
        if (!passwordEncoder.matches(vo.getPassword(), loginUser.getPassword())) {
            throw new BusinessException("原密码不正确");
        }
        // 修改密码
        SysUserEntity user = baseMapper.selectById(loginUser.getUserId());
        user.setPassword(passwordEncoder.encode(vo.getNewPassword()));
        baseMapper.updateById(user);
    }

    @Override
    public PageResult<SysUserVO> roleUserPage(SysRoleUserQuery query) {
         // 查询参数
        Map<String, Object> params = getParams(query);
        params.put("roleId", query.getRoleId());

        // 分页查询

        Page<SysUserEntity> objects = PageHelper.startPage(query.currentPage, query.size);
        params.put(Constant.PAGE, objects);

        // 数据列表
        List<SysUserEntity> list = baseMapper.getRoleUserList(params);

        return new PageResult<>(SysUserConvert.INSTANCE.convertList(list), objects.getTotal());
    }

    private Wrapper<SysUserEntity> getWrapper(SysUserQuery query) {
        LambdaQueryWrapper<SysUserEntity> wrapper = Wrappers.lambdaQuery();

        return wrapper;
    }
    private Map<String, Object> getParams(SysUserQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", query.getUsername());
        params.put("mobile", query.getMobile());
        params.put("gender", query.getGender());

        // 数据权限
        DataScopeUtils dataScopeUtils = new DataScopeUtils();
        DataScope dataScope = dataScopeUtils.getDataScope("t1", null);
        params.put(Constant.DATA_SCOPE,dataScope);
        return params;
    }

}
